
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// import baseurl from '../common/util';
let viewer, scene, camera, renderer, controls,canvas;



// export function initCesium() {
//     Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5YjdiMzE0OC04OGE5LTQ4NGEtODZkMC1kN2U1MmMyMWYwNzIiLCJpZCI6MTYwNjUsInNjb3BlcyI6WyJsZ24iLCJwciIsImFjdyIsImFzbCIsImFzciIsImFzdyIsImFzcyIsImdjIiwibHIiLCJsdyIsInRyIiwidHciLCJ1c2ciXSwiaWF0IjoxNjI2OTYwOTM1LCJleHAiOjE2Mjc1NjU3MzV9.VcNEmfaN_fYKeuLt7mXXQg77v-SRIIP7Cy-ZsgPuj5I'
//
//     viewer = new Cesium.Viewer('canvas3d', {
//         terrainProvider: Cesium.createWorldTerrain()
//     });
//
//     scene = viewer.scene;
//     camera = viewer.camera;
//     canvas = viewer.canvas;
//
//     // 禁用默认的事件处理器
//     scene.screenSpaceCameraController.enableRotate = false;
//     scene.screenSpaceCameraController.enableTranslate = false;
//     scene.screenSpaceCameraController.enableZoom = false;
//     scene.screenSpaceCameraController.enableTilt = false;
//     scene.screenSpaceCameraController.enableLook = false;
// }

function  stringtoHtml(str){
    var dom = document.createElement('div');
    dom.innerHTML = str;
    return dom;
}

export function init(ele) {

    // console.log( document.querySelector("div[cid='100']").clientWidth)
    // const container = document.getElementById('node28');
    // const container = document.getElementsByClassName("canvas3d")[0]
   let  container  = document.getElementsByName("canvas3d")[1];
    // console.log(container)
    // console.log(document.getElementsByName("canvas3d")[1])
    // console.log(document.getElementById('node33'))
    // let  container;
    let width=  800;
    let height = 800;
   if(ele && ele.includes("canvas3d")){

       // container = stringtoHtml(ele).querySelector("div[cid='100']");
       var obj = stringtoHtml(ele).querySelector("div[cid='100']");

       width = obj.style.width.slice(0, obj.style.width.length - 2);
       height = obj.style.height.slice(0, obj.style.height.length - 2);


   }else{
       // container =  document.querySelector("div[cid='100']")
       if(container){
           width = container.clientWidth
           height = container.clientHeight
       }
   }




    container.innerHTML=""
    // if(container){
    //     container.innerHTML=""
    // }
    // if(!container.style){
    //     container.setAttribute("id","node33");
    //     container.style.backgroundColor = "red";
    //     container.style.height = "600px"
    //     container.style.top = "144px";
    //     container.style.left ="266px"
    // }




    // Create scene
    scene = new THREE.Scene();
    // scene.background = new THREE.Color(0x000000);
    // scene.background = "";
    // Create camera
    scene.background = new THREE.Color(0x39759ba6);
    // scene.background.alpha = 0;
    camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
    camera.position.set(5, 6, 10);

    // camera.position.z = -2;
    // camera.position.y = 0;
    // camera.position.x = 0;
    // Create renderer
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);
    container.appendChild(renderer.domElement);

    // Add lights
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(ambientLight);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(1, 1, 1);
    scene.add(directionalLight);

    // Add OrbitControls
    controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;

    // Load GLB model
    const loader = new GLTFLoader();
    loader.load(
       //baseurl+ '/lib/jifang20241109.glb', // Make sure this path is correct
        function (gltf) {
            const model = gltf.scene;
            scene.add(model);


            // 添加特效，例如材料特效
            // 遍历模型的所有子元素
            model.traverse((child) => {
                console.log(child)
                if (child.isMesh) {
                    console.log(child.isMesh.name)
                    if("机柜B-005_(1)"==child.isMesh.name) {
                        // 为第一个找到的网格添加发光效果
                        child.material.emissive = new THREE.Color(0xFF0000);
                        child.material.emissiveIntensity = 0.8;
                        return;  // 只对第一个网格应用效果
                    }
                }
            });

            // 动画启动
            // if (gltf.animations && gltf.animations.length) {
            //     mixer = new THREE.AnimationMixer(model);
            //     for (const animation of gltf.animations) {
            //         mixer.clipAction(animation).play();
            //     }
            // }

            // Center the model
            const box = new THREE.Box3().setFromObject(model);
            const center = box.getCenter(new THREE.Vector3());
            model.position.sub(center);

            // Scale the model to fit the screen
            const size = box.getSize(new THREE.Vector3());
            const maxDim = Math.max(size.x, size.y, size.z);
            const scale = 5 / maxDim;
            // model.scale.multiplyScalar(scale);
            model.scale.set(1,1, 1);
            // document.getElementById('canvas3d').textContent = 'Model loaded successfully';
        },
        function (xhr) {
            console.log((xhr.loaded / xhr.total * 100) + '% loaded');
        },
        function (error) {
            console.error('An error happened', error);
            // document.getElementById('canvas3d').textContent = 'Error loading model';
        }
    );

    // Handle window resize
    window.addEventListener('resize', onWindowResize(ele), false);
}

function onWindowResize(ele) {
    // const container = document.getElementById('canvas3d').parentNode;
    // const container = document.getElementById('canvas3d').parentNode;
    let  container = document.getElementsByName("canvas3d")[1];
    let width = 800;
    let height = 800;
    // const container = document.getElementById('node28');
    // const container = document.getElementsByClassName("canvas3d")[0]
    if(ele&&ele.includes("canvas3d")){
        var obj  = stringtoHtml(ele).querySelector("div[cid='100']");
        width = obj.style.width.slice(0, obj.style.width.length - 2);
        height = obj.style.height.slice(0, obj.style.height.length - 2);


    }else{
        // container =  document.querySelector("div[cid='100']")
        if(container){
            width = container.clientWidth
            height = container.clientHeight
        }
    }
    // const  container = document.querySelector("div[cid='100']")
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height);
}

export	function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
}


